﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BudgetSV.Common;
using System.Linq;
using BudgetData;

namespace BudgetSV.admin.manager
{
    public partial class manager_edit : ManagePage
    {
        string defaultpassword = "0|0|0|0"; //默认显示密码
        private string action = DTEnums.ActionEnum.Add.ToString(); //操作类型
        private long id = 0;
        public string roleHtml = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            string _action = DTRequest.GetQueryString("action");
            if (!string.IsNullOrEmpty(_action) && _action == DTEnums.ActionEnum.Edit.ToString())
            {
                this.action = DTEnums.ActionEnum.Edit.ToString();//修改类型
                if (!long.TryParse(Request.QueryString["id"] as string, out this.id))
                {
                    JscriptMsg("传输参数不正确！", "back", "Error");
                    return;
                }
                
            }
            if (!Page.IsPostBack)
            {
                ChkAdminLevel("manager_list", DTEnums.ActionEnum.View.ToString()); //检查权限

                var model = GetAdminInfo();
                RoleBind(this.id, model.role_type);

                DropDownList1Bind();//绑定组织机构
                ///////DepartTreeBind(GetAdminInfo().depart_id); //绑定部门列表
                if (action == DTEnums.ActionEnum.Edit.ToString()) //修改
                {
                    ShowInfo(this.id);
                }
            }
        }

        #region 绑定组织机构列表=============================

        private void DropDownList1Bind()
        {
            IList<Organization> dt = GetList(GetAdminInfo().org_id);

            this.DropDownList1.Items.Clear();
            this.DropDownList1.Items.Add(new ListItem("未选择", ""));
            foreach (var dr in dt)
            {
                string Id = dr.id.ToString();       // dr["id"].ToString();
                int ClassLayer = dr.class_layer;    // int.Parse(dr["class_layer"].ToString());
                string Title = dr.name;             // dr["name"].ToString().Trim();

                if (ClassLayer == 1)
                {
                    this.DropDownList1.Items.Add(new ListItem(Title, Id));
                }
                else
                {
                    Title = "├ " + Title;
                    Title = Utils.StringOfChar(ClassLayer - 1, "　") + Title;
                    this.DropDownList1.Items.Add(new ListItem(Title, Id));
                }
            }
        }
        #endregion

        #region 绑定部门列表=============================

        private void DepartTreeBind(long orgid)
        {
            IList<Department> dt = GetDepartList(orgid);

            this.ddlDepartId.Items.Clear();
            this.ddlDepartId.Items.Add(new ListItem("未选择", ""));
            foreach (var dr in dt)
            {
                string Id = dr.id.ToString();       // dr["id"].ToString();
                int ClassLayer = dr.class_layer;    // int.Parse(dr["class_layer"].ToString());
                string Title = dr.name;             // dr["name"].ToString().Trim();

                if (ClassLayer == 1)
                {
                    this.ddlDepartId.Items.Add(new ListItem(Title, Id));
                }
                else
                {
                    Title = "├ " + Title;
                    Title = Utils.StringOfChar(ClassLayer - 1, "　") + Title;
                    this.ddlDepartId.Items.Add(new ListItem(Title, Id));
                }
            }
        }
        #endregion

        #region 角色类型=================================

        private void RoleBind(long managerid, int role_type)
        {
            var m = GetAdminInfo();
            List<ManagerRole> roles = Mod.GetList<ManagerRole>(c=>c.org_id==m.org_id);
            List<ManagerRole> rls = Mod.GetList<ManagerRole>("select * from ManagerRole where id in (SELECT role_id from ManagerRoleLK WHERE manager_id="+ managerid + ")");
            string v = ",";
            string tx = "";
            foreach (var r in roles) {
                var h = rls.FirstOrDefault(c=>c.id==r.id);
                if (h != null)
                {
                    v += h.id + ",";
                    tx += h.role_name + ",";
                    roleHtml += "<tr style=\"height:25px;\">" +
                            "<td style=\"width:20%;text-align:center;\">" +
                                "<input class=\"roleit\" type=\"checkbox\" value=\"" + r.id + "\" data-name=\"" + r.role_name + "\" checked=\"checked\" /></td>" +
                            "<td style=\"width:80%;\">" + r.role_name + "</td>" +
                        "</tr>";
                }
                else
                {
                    roleHtml += "<tr style=\"height:25px;\">" +
                            "<td style=\"width:20%;text-align:center;\">" +
                                "<input class=\"roleit\" type=\"checkbox\" value=\"" + r.id + "\" data-name=\"" + r.role_name + "\" /></td>" +
                            "<td style=\"width:80%;\">" + r.role_name + "</td>" +
                        "</tr>";
                }
            }
            RoleIds.Value = v;
            ORoleIds.Value = v;
            Roles.Text = tx;
        }
        #endregion

        #region 赋值操作=================================

        private void ShowInfo(long _id)
        {
            Manager model = Mod.GetModel<Manager>(c=>c.id==_id);
            //ddlDepartId.SelectedValue = model.depart_id.ToString();
            //ddlRoleId.SelectedValue = model.role_id.ToString();
            DropDownList1.SelectedValue = model.org_id.ToString();
            DepartTreeBind(Convert.ToInt64(DropDownList1.SelectedValue));
            ddlDepartId.SelectedValue = model.depart_id.ToString();
            txtSortId.Text = model.sort.ToString();
            if (model.is_lock == 0)
            {
                cbIsLock.Checked = true;
            }
            else
            {
                cbIsLock.Checked = false;
            }
            cbIsLeader.Checked = model.isleader;
            txtUserName.Text = model.user_name;
            //txtUserName.ReadOnly = true;
            txtUserName.Attributes.Remove("ajaxurl");
            if (!string.IsNullOrEmpty(model.password))
            {
                txtPassword.Attributes["value"] = txtPassword1.Attributes["value"] = defaultpassword;
            }
            txtRealName.Text = model.real_name;
            txtTelephone.Text = model.telephone;
            txtEmail.Text = model.email;
        }
        #endregion

        #region 增加操作=================================
        private bool DoAdd()
        {
            var adm = GetAdminInfo();
            Manager model = new Manager();
            //model.role_id = int.Parse(ddlRoleId.SelectedValue);
            //model.role_type = new BLL.ManagerRoleBLL().GetModel(model.role_id).role_type;
            if (cbIsLock.Checked == true)
            {
                model.is_lock = 0;
            }
            else
            {
                model.is_lock = 1;
            }
            model.isleader = cbIsLeader.Checked;
            //检测用户名是否重复
            var nunm = txtUserName.Text.Trim();
            var h = Mod.GetModel<Manager>(c => c.user_name == nunm);
            if (h!=null)
            {
                return false;
            }
            model.user_name = txtUserName.Text.Trim();
            //获得6位的salt加密字符串
            model.salt = Utils.GetCheckCode(6);
            //以随机生成的6位字符串做为密钥加密
            model.password = DESEncrypt.Encrypt(txtPassword.Text.Trim(), model.salt);
            model.real_name = txtRealName.Text.Trim();
            model.telephone = txtTelephone.Text.Trim();
            model.email = txtEmail.Text.Trim();
            model.add_time = DateTime.Now;
            if (!string.IsNullOrEmpty(ddlDepartId.SelectedValue)) model.depart_id = int.Parse(ddlDepartId.SelectedValue);
            model.org_id = int.Parse(DropDownList1.SelectedValue);
            model.role_type = 2;
            model.creator = adm.id;
            model.creator_org = adm.org_id;
            model.sort = int.Parse(txtSortId.Text.Trim());

            model = Mod.Add(model);
            if (model.id > 0)
            {
                //角色
                var rolev = RoleIds.Value;
                var role = rolev.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var r in role)
                {
                    var mr = new ManagerRoleLK
                    {
                        manager_id = model.id,
                        role_id = Convert.ToInt64(r),
                        addtime = DateTime.Now,
                        addmenager = adm.id
                    };

                    Mod.Add(mr);
                }

                this.id = model.id;
                //if (rolev.Length > 0) {
                //    var ar = rolev.Split(',');
                //    string sqlsr = "delete from ManagerRoleLK where manager_id = "+ model.id + ";";
                //    foreach (var a in ar) {
                //        if (!string.IsNullOrEmpty(a)) {
                //            sqlsr += "INSERT INTO ManagerRoleLK (manager_id,role_id,addtime,addmenager) VALUES("+ model.id + "," + a + ",GETDATE()," + adm.id + ")";
                //        }
                //    }
                //    new BLL.ManagerBLL().SaveRoles(sqlsr);
                //}

                AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "添加管理员:" + model.user_name); //记录日志
                return true;
            }
            return false;
        }
        #endregion

        #region 修改操作=================================
        private bool DoEdit(long _id)
        {
            var adm = GetAdminInfo();
            bool result = false;
            Manager model = Mod.GetModel<Manager>(c=>c.id==_id);

            //model.role_id = int.Parse(ddlRoleId.SelectedValue);
            //model.role_type = new BLL.ManagerRoleBLL().GetModel(model.role_id).role_type;
            if (cbIsLock.Checked == true)
            {
                model.is_lock = 0;
            }
            else
            {
                model.is_lock = 1;
            }
            model.isleader = cbIsLeader.Checked;

            model.user_name = txtUserName.Text.Trim();
            //判断密码是否更改
            if (txtPassword.Text.Trim() != defaultpassword)
            {
                //获取用户已生成的salt作为密钥加密
                model.password = DESEncrypt.Encrypt(txtPassword.Text.Trim(), model.salt);
            }
            model.real_name = txtRealName.Text.Trim();
            model.telephone = txtTelephone.Text.Trim();
            model.email = txtEmail.Text.Trim();
            if (!string.IsNullOrEmpty(ddlDepartId.SelectedValue))
                model.depart_id = int.Parse(ddlDepartId.SelectedValue);
            else
                model.depart_id = 0;
            model.org_id = int.Parse(DropDownList1.SelectedValue);
            model.creator = adm.id;
            model.creator_org = adm.org_id;
            model.sort = int.Parse(txtSortId.Text.Trim());

            if (Mod.Update(model)>0)
            {
                var rolev = RoleIds.Value;
                var orolev = ORoleIds.Value;
                if (orolev != rolev)
                {
                    Mod.Executed("delete from ManagerRoleLK where manager_id="+ model.id);
                    var role = rolev.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var r in role)
                    {
                        var mr = new ManagerRoleLK
                        {
                            manager_id = model.id,
                            role_id = Convert.ToInt64(r),
                            addtime = DateTime.Now,
                            addmenager = adm.id
                        };
                        Mod.Add(mr);
                    }
                    //var lk = Mod.GetList<ManagerRoleLK>(t => t.manager_id == model.id);
                    //foreach(var l in lk)
                    //{
                    //    l.State = System.Data.Entity.EntityState.Deleted;
                    //}

                    //var role = rolev.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    //foreach(var r in role)
                    //{
                    //    var mr = new ManagerRoleLK
                    //    {
                    //        manager_id = model.id,
                    //        role_id = Convert.ToInt64(r),
                    //        addtime = DateTime.Now,
                    //        addmenager = adm.id
                    //    };

                    //    lk.Add(mr);
                    //}
                    //lbll.Update(lk);

                    //string sqlsr = "delete from ManagerRoleLK where manager_id = " + model.id + ";";
                    //if (rolev.Length > 0)
                    //{
                    //    var ar = rolev.Split(',');
                    //    foreach (var a in ar)
                    //    {
                    //        if (!string.IsNullOrEmpty(a))
                    //        {
                    //            sqlsr += "INSERT INTO ManagerRoleLK (manager_id,role_id,addtime,addmenager) VALUES(" + model.id + "," + a + ",GETDATE()," + adm.id + ")";
                    //        }
                    //    }
                    //    new BLL.ManagerBLL().SaveRoles(sqlsr);
                    //}
                }
                AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "修改管理员:" + model.user_name); //记录日志
                result = true;
            }

            return result;
        }
        #endregion

        //保存
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (action == DTEnums.ActionEnum.Edit.ToString()) //修改
            {
                ChkAdminLevel("manager_list", DTEnums.ActionEnum.Edit.ToString()); //检查权限
                if (!DoEdit(this.id))
                {
                    JscriptMsg("保存过程中发生错误！", "", "Error");
                    return;
                }
                JscriptMsg("修改管理员信息成功！", "manager_list.aspx", "Success");
            }
            else //添加
            {
                ChkAdminLevel("manager_list", DTEnums.ActionEnum.Add.ToString()); //检查权限
                if (!DoAdd())
                {
                    JscriptMsg("保存过程中发生错误！", "", "Error");
                    return;
                }
                JscriptMsg("添加管理员信息成功！", "manager_list.aspx", "Success");
            }
        }
        protected void departid_change(object sender, EventArgs e) {
            var org_id = Convert.ToInt64(this.DropDownList1.SelectedValue);
            DepartTreeBind(org_id);
            Manager model = GetAdminInfo(); //取得管理员信息
            RoleBind(this.id, model.role_type);
        }
    }
}